
const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')

const navTypeModel = require("../models/nav_type")
const navTypeinfo = navTypeModel(sequelize);

const userModel = require("../models/email_user")
const userinfo = userModel(sequelize);

const navModel = require("../models/nav_list")
const navinfo = navModel(sequelize);


// 分页
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;

        let where = {}
        let userid = await getUserID(ctx);
        // 有正确的token
        if (userid) {
            where = { userid: userid }
        }

        let navData = await navTypeinfo.findAndCountAll(
            {
                order: [  //排序 DESC ASC
                    ['sort', 'ASC']
                ],
                attributes: {
                    exclude: ['deletedAt', 'updatedAt', 'orderid', 'createdAt'],
                },
                where: where,
            }
        );
        ctx.body = util.resultSuccess({ data: navData });
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ data: null });
    }
})

// 类型列表
router.get('/list', async (ctx) => {
    try {

        let reqQuery = ctx.request.query;
        let where = {}
        let userid = await getUserID(ctx);
        // 有正确的token
        if (userid) {
            where = { userid: userid }
        }

        let navData = await navTypeinfo.findAll(
            {
                order: [  //排序 DESC ASC
                    ['sort', 'ASC']
                ],
                attributes: {
                    exclude: ['deletedAt', 'updatedAt', 'sort', 'createdAt', 'userid'],
                },
                where: where,
            }
        );
        ctx.body = util.resultSuccess({ data: navData });
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ data: null });
    }
})
/**
 * 修改
 * */
router.post('/editById', async (ctx) => {
    try {
        ctx
            .validateBody("id")
            .required("id不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("ntitle")
            .required("标题不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("nurl")
            .required("地址不能为空")
            .isString()
            .trim()
        let reqBody = ctx.request.body;
        console.log(reqBody);
        let requestData = await navTypeinfo.update({
            ntitle: reqBody.ntitle ? reqBody.ntitle : '',
            ndetail: reqBody.ndetail ? reqBody.ndetail : '',
            typeid: reqBody.typeid ? reqBody.typeid : '',
            nurl: reqBody.nurl ? reqBody.nurl : '',
        }, {
            where: {
                id: reqBody.id
            }
        })
        if (requestData[0] > 0) {
            ctx.body = util.resultSuccess({ message: '修改成功', data: null });
        } else {
            ctx.body = util.resultError({ code: 0, message: '修改失败,id错误', data: null });
        }

    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})

/**
 * 新增
 * */
router.post('/add', async (ctx) => {
    try {

        let reqBody = ctx.request.body;
        let requestData = null, bodyMsg = '', bodyData
        if (reqBody.typeid) {
            requestData = await navTypeinfo.update({
                typename: reqBody.typename ? reqBody.typename : '',
                sort: reqBody.sort ? reqBody.sort : 100,
            }, {
                where: {
                    typeid: reqBody.typeid
                }
            })
            if (requestData[0] > 0) {
                bodyMsg = '修改成功'
            } else {
                bodyMsg = '修改失败'
            }
        } else {
            let userid = await getUserID(ctx);
            requestData = await navTypeinfo.create({
                typeid: getuuid(),
                userid: userid,
                typename: reqBody.typename ? reqBody.typename : '',
                sort: reqBody.sort ? reqBody.sort : 100,
            })
            if (requestData.dataValues) {
                bodyMsg = '添加成功'
            } else {
                bodyMsg = '添加失败'
            }
        }
        ctx.body = util.resultSuccess({ message: bodyMsg, data: '' });

    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})

/**
 * 删除
 * */
router.post('/delById', async (ctx) => {
    try {
        ctx
            .validateBody("id")
            .required("id不能为空")
            .isString()
            .trim()


        let navData = await navinfo.findAll(
            {
                where: {
                    typeid: ctx.vals.id
                },
            }
        );
        if (navData.length > 0) {
            ctx.body = util.resultError({ message: '该分类下面有链接，不能删除' });
            return
        }

        let requestData = await navTypeinfo.destroy({
            where: {
                typeid: ctx.vals.id
            }
        })
        if (requestData > 0) {
            ctx.body = util.resultSuccess({ message: '删除成功' });
        } else {
            ctx.body = util.resultError({ code: 0, message: '删除失败,该类型不存在', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})


async function getUserID(ctx) {
    let token = Cookie('token', ctx.request.header.cookie)
    if (!token) {
        return ''
    }
    let userData = await userinfo.findOne(
        {
            where: {
                token: token
            },
        }
    );
    console.log('userData', userData.dataValues._id);
    if (userData) {
        return userData.dataValues._id
    } else {

        return '-1'
    }
}
function Cookie(name, cookies) {
    var CookieValue = null;
    if (cookies) {
        var Cookies = cookies.split(";");
        for (var i = 0; i < Cookies.length; i++) {
            var Cookie = (Cookies[i] || "").replace(/^\s+|\s+$/g, "");
            //这个if写的屌
            if (Cookie.substring(0, name.length + 1) == (name + '=')) {
                CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return CookieValue;
}
function getuuid() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    var uuid = s.join("");
    return uuid;
}
module.exports = router.routes();